﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using NLog;
using Codebricks.Db;

namespace KBSearch
{
    public class Spider
    {
        private Logger Log = LogManager.GetCurrentClassLogger();

        private int PagingSize { get; set; }
        private string SearchQuery { get; set; }
        
        private string searchSql = @" Select * 
                                      From   articles 
                                      where  is_draft=0 
                                        And  DATE(CURDATE())>=DATE(Publish_Start_Date) 
                                        And  DATE(CURDATE())<DATE(Publish_End_Date) 
                                        And MATCH (Title,Content)  AGAINST(@SearchPhrase  IN BOOLEAN MODE )
                                        limit {0},{1}
                                      ";
        private string searchResultCountSql = @" Select count(*) TotalResultNumber
                                      From   articles 
                                      where  is_draft=0 
                                        And  DATE(CURDATE())>=DATE(Publish_Start_Date) 
                                        And  DATE(CURDATE())<DATE(Publish_End_Date) 
                                        And MATCH (Title,Content)  AGAINST(@SearchPhrase  IN BOOLEAN MODE )                                        
                                      ";

        public Spider(string query, int pageSize)
        {
            List<string> searchWords = query.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
            SearchQuery = "";
            foreach (string word in searchWords)
            {
                SearchQuery += word + "* ";
            }
            PagingSize = pageSize;
        }

        
        public int ResultCount()
        {
            try
            {                                
                MysqlParameterCollection col = new MysqlParameterCollection();
                col.Add("SearchPhrase", SearchQuery);
                DataTable dt = MySqlDb.Select(searchResultCountSql, col);
                if (dt.Rows.Count == 1 )
                {
                    return Convert.ToInt32(dt.Rows[0]["TotalResultNumber"]);
                }                
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
            }
            return 0;
        }

        public List<SpiderResult> Search(int page=1 )
        {
            List<SpiderResult> results = new List<SpiderResult>();
            try
            {
                int currentPage = (page - 1) * PagingSize;
                List<string> searchWords = SearchQuery.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries).ToList();
                string betterSearchQuery = "";
                foreach (string word in searchWords)
                {
                    betterSearchQuery += word + "* ";
                }
                MysqlParameterCollection col = new MysqlParameterCollection();
                col.Add("SearchPhrase", betterSearchQuery);
                DataTable dt = MySqlDb.Select(String.Format(searchSql, currentPage, PagingSize), col);
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {                        
                        SpiderResult result = new SpiderResult()
                        {
                            Content = row["Content"].ToString(),
                            Title = row["Title"].ToString(),
                            Id = Convert.ToInt32( row["Id"] )
                        };
                        results.Add(result);
                    }
                }                
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);                
            }
            return results;
        }
    }

    public class SpiderResult
    {
        public string Title { get; set; }
        public string Content { get; set; }
        public int Id{ get; set; }
    }

    
}
